new Vue({
    el: '#app',
    mixins: [Save],//组件配置文件，路径/utils/components.js
        data() {
            return {
                supply_unitprice: {},
                dataForm: {
                    Amount: '0',
                    Paid_Amount: '0',
                    Remain_Amount: '0',
                    Quantity: '0',
                    Detailed_Address: '',
                    Trading_SerialNumber: '',
                    Shipment_Method_SerialNumber: '',
                    Transport_Method_SerialNumber: '',
                    Payment_Method_SerialNumber: '',
                    Supplementary_Provisions: '',
                    Supplementary_Explanation: '',
                    Supply_Unit_Price_SerialNumber: ''
                },
            Trading_SerialNumber: [],
            Payment_Method_SerialNumber: [],
            Shipment_Method_SerialNumber: [],
            Transport_Method_SerialNumber: [],
            article_info: [], // 可选商品
            transport_method: [], // 运输方式
            shipment_method: [], // 装运方式
            payment_method: [], // 付款方式
            article_unit: [], // 单位
            enterprise_info: [],// 企业
            enterprise_info1: [],// 企业1
                city: [],
                trading: [],// 付款类型
                // 交易数量组件的安全边界
                minQty: 0,
                maxQty: 0,
                stepQty: 1,
            }
        },
    mounted() {
        /**
         * 组件配置文件中自动执行方法
         * 1.this.init(); //初始化文件
         * 2.this.getData(); //仅修改时执行，根据BOM配置属性查询
         */
        this.getList();
    },
    methods: {
        documentLoadFinished() { 
            this.getList();
        },
        getList() { // 初始化数据
            // Modify 模式下，优先使用主表中的 Supply_Unit_Price_SerialNumber
            const supplyKey = this.action === 'Modify'
                ? ((this.dataForm && this.dataForm.Supply_Unit_Price_SerialNumber) || '')
                : this.nodeKey;
            if (!supplyKey) {
                return;
            }
            this.dataForm.Supply_Unit_Price_SerialNumber = supplyKey;
            // 查询主数据
            httpRequest({
                url: '/generalBusiness/queryMultiTableByCondition',
                data: {
                    Data: JSON.stringify([{
                        tableName: 'supply_unitprice',
                        Condition: utf8ToBase64(`Supply_Unit_Price_SerialNumber='${supplyKey}'`),
                    }, {
                        tableName: 'supply_unitprice_mapping_payment',
                        Condition: utf8ToBase64(`Row_Status='0' AND Supply_Unit_Price_SerialNumber='${supplyKey}'`),
                    }, {
                        tableName: 'supply_unitprice_mapping_shipment',
                        Condition: utf8ToBase64(`Row_Status='0' AND Supply_Unit_Price_SerialNumber='${supplyKey}'`),
                    }, {
                        tableName: 'supply_unitprice_mapping_trading',
                        Condition: utf8ToBase64(`Row_Status='0' AND Supply_Unit_Price_SerialNumber='${supplyKey}'`),
                    }, {
                        tableName: 'supply_unitprice_mapping_transport',
                        Condition: utf8ToBase64(`Row_Status='0' AND Supply_Unit_Price_SerialNumber='${supplyKey}'`),
                    }, {
                        tableName: 'article_info',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'transport_method',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'shipment_method',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'payment_method',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'article_unit',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'enterprise_info',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }])
                },
            }).then(data => {
                const { supply_unitprice, supply_unitprice_mapping_payment, supply_unitprice_mapping_shipment, supply_unitprice_mapping_trading, supply_unitprice_mapping_transport, article_info, transport_method, shipment_method, payment_method, article_unit, enterprise_info } = data;
                this.supply_unitprice = supply_unitprice[0];
                this.Trading_SerialNumber = supply_unitprice_mapping_trading.map(i => i.Trading_SerialNumber);
                this.Payment_Method_SerialNumber = supply_unitprice_mapping_payment.map(i => i.Payment_Method_SerialNumber);
                this.Shipment_Method_SerialNumber = supply_unitprice_mapping_shipment.map(i => i.Shipment_Method_SerialNumber);
                this.Transport_Method_SerialNumber = supply_unitprice_mapping_transport.map(i => i.Transport_Method_SerialNumber);
                this.article_info = article_info;
                this.transport_method = transport_method;
                this.shipment_method = shipment_method;
                this.payment_method = payment_method;
                this.article_unit = article_unit;
                this.enterprise_info = enterprise_info;
                // 计算数量组件边界，避免初始NaN
                const toNum = v => { const n = Number(v); return Number.isFinite(n) ? n : 0; };
                const r = toNum(this.supply_unitprice.Remain_Quantity);
                const s = toNum(this.supply_unitprice.Start_Quantity);
                const u = toNum(this.supply_unitprice.Unit_Quantity);
                this.minQty = (s > 0 && r > s) ? s : r;
                this.maxQty = r > 0 ? r : 0;
                this.stepQty = u > 0 ? u : 1;

                // Add 模式初始化默认数量；Modify 模式保留原值
                if (this.action === 'Add') {
                    this.dataForm.Quantity = supply_unitprice[0].Start_Quantity;
                    this.changeQuantity(this.dataForm.Quantity);
                } else if (this.action === 'Modify') {
                    // 若缺少金额，则根据当前单价重新计算
                    if (!this.dataForm.Amount || this.dataForm.Amount === '0') {
                        this.changeQuantity(this.dataForm.Quantity || 0);
                    }
                }
            }).catch(xhr => {
                this.$message({
                    message: '系统错误，请联系开发者!',
                    type: 'error'
                })
            })

            httpRequest({
                url: '/generalBusiness/generalQueryBySQLSerialNumber',
                data: {
                    SQLSerialNumber: 'f_user_mapping_enterprise',
                    Condition: utf8ToBase64(getCookie('user')),
                    ExtensionCondition: ''
                }
            }).then(data => {
                this.enterprise_info1 = data;
                const currentEnterpriseId = (data && data[0]) ? data[0].Enterprise_Info_SerialNumber : '';
                this.$set(this.dataForm, 'Enterprise_Info_SerialNumber', currentEnterpriseId);
            }).catch(xhr => {
                this.$message({
                    message: '系统错误，请联系开发者!',
                    type: 'error'
                })
            })

            // 地址 
            $.ajax({
                url: absolutepath() + 'admin/data/dtree.json',
                type: 'GET',
                success: (data) => {
                    this.city = data;
                },
            })

            $.ajax({
                url: absolutepath() + 'admin/data/trading.json',
                type: 'GET',
                success: (data) => {
                    this.trading = data;
                },
            })
        },
        changeCity(val) {
            this.dataForm.ProvinceNumber = val ? (val.substring(0, 2) + '0000') : '';
            this.dataForm.CityNumber = val ? (val.substring(0, 4) + '00') : '';
            this.dataForm.Detailed_Address = '';
        },
        changeChildDataForm(val, formName) { //付款方式
            this[formName] = val.map(i => {
                let obj = new Object();
                obj[formName] = i
                return obj;
            })
        },
        changeQuantity(val) { //销售数量
            const qty = Number(val || 0);
            const unitPrice = Number((this.supply_unitprice && this.supply_unitprice.Unit_Price) || 0);
            if (isNaN(qty) || isNaN(unitPrice)) {
                this.dataForm.Amount = 0;
                return;
            }
            this.dataForm.Amount = accMul(qty, unitPrice);
        },
        async handleSubmit() { //点击提交
            const allValid = await this.validateAllForms();
            if (allValid) {
                // this.loading = true;
                try {
                    const supply_unitprice = deepClone(this.supply_unitprice);

                    // 一致性校验：扣减前校验剩余量是否足够
                    const reqQty = Number(this.dataForm.Quantity || 0);
                    const remainQty = Number(supply_unitprice.Remain_Quantity || 0);
                    if (isNaN(reqQty) || reqQty <= 0) {
                        this.$message.error('交易数量无效');
                        this.loading = false;
                        return;
                    }
                    if (remainQty < reqQty) {
                        this.$message.error('剩余量不足，无法提交申请');
                        this.loading = false;
                        return;
                    }

                    //计算剩余数量
                    supply_unitprice.Remain_Quantity = accSub(supply_unitprice.Remain_Quantity, this.dataForm.Quantity);
                    supply_unitprice.Sales_Quantity = accAdd(supply_unitprice.Sales_Quantity, this.dataForm.Quantity);
                    // 申请阶段不写入已收款，仅在付款流程更新
                    this.$set(this.dataForm, 'Paid_Amount', '0');
                    // 剩余金额 = 成交金额 - 已收款（此时为 0）
                    this.$set(this.dataForm, 'Remain_Amount', this.dataForm.Amount);

                    const lJSONObject_DataSet = this.generateStructure();

                    lJSONObject_DataSet['Modify'] = { supply_unitprice: [supply_unitprice] };

                    httpRequest({
                        contentType: 'JSON',
                        url: '/generalBusiness/generalSaveByRequestBody',
                        data: JSON.stringify({
                            Data: lJSONObject_DataSet
                        })
                    }).then(res => {
                        if (res.Status == "success") {
                            this.$message.success("提交成功");
                            window.location.href = './index.html';
                        } else {
                            this.$message.error("提交失败，请重试！");
                        }
                    }).catch(xhr => {
                        this.$message.error("系统错误，请联系开发者!")
                    }).finally(() => {
                        this.loading = false;
                    })
                } catch (error) {
                    console.error(error);
                    this.$message.error("系统错误，请联系开发者!")
                    this.loading = false;
                }
            } else {
                this.$message({
                    message: '存在未填写的必填项！',
                    type: 'warning'
                });
            }
        },
        async handleResubmit() { // 修改并重新提交：状态重置为待审核
            const allValid = await this.validateAllForms();
            if (!allValid) {
                this.$message({ message: '存在未填写的必填项！', type: 'warning' });
                return;
            }
            try {
                // 以提交页的修改模式为准，nodeKey 为对应订单主键
                const data = await generalApi.generalQueryByTableNameWithOriginal({
                    Data: 'supply_order',
                    Condition: `Supply_Order_SerialNumber='${this.nodeKey}'`
                });
                if (!Array.isArray(data) || data.length !== 1) {
                    this.$message.error('未找到申请记录或存在重复记录');
                    return;
                }
                const origin = data[0];
                // 避免使用页面的 dataForm 覆盖原始的报价编号等关键外键字段
                const updated = {
                    ...origin,
                    ...this.dataForm,
                    Supply_Order_SerialNumber: this.nodeKey,
                    Supply_Unit_Price_SerialNumber: origin.Supply_Unit_Price_SerialNumber,
                    // 保留原有已收款，仅调整剩余金额：Amount - 原 Paid_Amount
                    Paid_Amount: origin.Paid_Amount,
                    Remain_Amount: accSub(this.dataForm.Amount, origin.Paid_Amount),
                };
                // 重置为待审核
                updated.Row_Status = '0';

                const dataset = {
                    Modify: { supply_order: [updated] },
                    Add: {
                        base_operation_log: [{
                            Operation_Type: '0',
                            Operation_Path: getRelativePath(),
                            Operation_Description: '采购修改并重新提交（状态置为待审核）',
                            Operation_Main: JSON.stringify({
                                Supply_Order_SerialNumber: this.nodeKey,
                                Supply_Unit_Price_SerialNumber: origin.Supply_Unit_Price_SerialNumber,
                                Action: 'modify_resubmit_purchase'
                            }),
                            Operation_Interface: 'generalSaveByRequestBody',
                            Operation_IP: getIpAddress()
                        }]
                    }
                };

                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                if (res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status === 'success')))) {
                    this.$message.success('已重新提交该申请');
                    window.location.href = './index.html';
                } else {
                    const msg = (res && (res.Message || res.Error || res.msg)) || '保存失败';
                    this.$message.error(msg);
                }
            } catch (error) {
                console.error(error);
                this.$message.error('系统错误，请联系开发者!');
            }
        }
    }
})
